package com.hejing.线程安全问题;

/**
 * ClassName: WindowTest01
 * Package: com.hejing.线程安全问题
 * Description:
 *      使用继承Thread的方式，实现卖票
 *      使用同步代码块 synchronized 处理出现线程安全问题(比如 案例中出现的错票、重票的情况)。
 * @Author: HeJing
 * @Create: 2023-04-14 19:31
 * @Version: 1.0
 */
public class WindowWithSynchronizedTest01 {
    public static void main(String[] args) {
        SaleTicket01WithSyn s1 = new SaleTicket01WithSyn();
        SaleTicket01WithSyn s2 = new SaleTicket01WithSyn();
        SaleTicket01WithSyn s3 = new SaleTicket01WithSyn();

        s1.setName("窗口1");
        s2.setName("窗口2");
        s3.setName("窗口3");

        s1.start();
        s2.start();
        s3.start();
    }
}

class SaleTicket01WithSyn extends Thread {

    static int ticket = 100;
    static Object obj = new Object();
    @Override
    public void run() {
        while(true) {
            try{
                Thread.sleep(10);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            // synchronized(obj) {
            synchronized(SaleTicket01WithSyn.class) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "售票，票号: " + (101 - ticket));
                    ticket--;
                } else break;
            }
        }
    }
}


















